﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLocalChurch.Business;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;
using MyLocalChurch.Models.Enumerations;
using MyLocalChurch.Models.KidsChurch;
using MyLocalChurch.Models.Resources;
using MyLocalChurch.Resources;
using RKConsulting.Helpers;
using RKConsulting.Web.Helpers;

namespace MyLocalChurch.KidsChurch
{
    public partial class CreateGuardian : System.Web.UI.Page
    {
        private readonly MyContext _context = MyContextSingleton.Instance;

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
                return;

            ddlGender.BindEnumValues<Gender>();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                Session[ImageHandler.SessionName] = null;
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
                return;

            var guardian = new Guardian
                {
                    FirstName = txtFirstName.Text,
                    MiddleName = txtMiddleName.Text,
                    LastName = txtLastName.Text,
                    NickName = txtNickName.Text,
                    Gender = (int)EnumHelper.Parse<Gender>(ddlGender.SelectedValue),
                    BirthDate = dpBirthDate.SelectedDate,
                    MobileNumber = txtMobileNumber.Text,
                    EmailAddress = txtEmailAddress.Text,
                    AdditionalInformation = txtAdditionalInformation.Text,
                    Photo = PhotoManager.CreatePhotoFromFileUploadOrSession(fileUploadPhoto, HttpContext.Current),
                    CreatedBy = SystemConstants.User,
                    CreatedDate = DateTime.Now
                };

            guardian.Barcodes.Add(BarcodeManager.GenerateBarcode(_context));

            _context.Guardians.Add(guardian);
            _context.SaveChanges();

            Response.Redirect("GuardiansList.aspx");
        }

        protected void btnPhotoPreview_Click(object sender, EventArgs e)
        {
            Session[ImageHandler.SessionName] = fileUploadPhoto.FileBytes;
            var imageHandlerUrl = ConfigurationManager.AppSettings[AppSettingKeys.ImageHandlerUrl];
            imagePreview.ImageUrl = imageHandlerUrl;
        }
    }
}